import 'package:async/async.dart';
import 'package:boss/common/common.dart';
import 'package:boss/main.dart';
import 'package:boss/models/store_area.dart';
import 'package:boss/models/store_table.dart';
import 'package:boss/ui/page/tableManagement/page/plusBatchTable/model/batchTable.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/sortList/sort_item_data.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class TableProvider extends ChangeNotifier {
  List<StoreArea> storeAreas = [];

  //初始化区域桌台数据
  Future<Result<List<StoreArea>>> initData() async {
    try {
      var areaTableResponse = await api.queryStoreTableArea();

      if (!areaTableResponse.successful()) {
        return Result.error(areaTableResponse.msg);
      }

      storeAreas = areaTableResponse.data;
      notifyListeners();

      return Result.value(areaTableResponse.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  //添加新的桌台
  Future<bool> plusStoreTable(StoreTable storeTable) async {
    if (!checkStoreTable(storeTable)) return false;

    try {
      showLoadingToast();

      var result = await api.addStoreTable({
        'tableName': storeTable.tableName,
        'maxPerson': storeTable.maxPerson,
        'areaId': storeTable.areaId,
        'areaName': storeTable.areaName,
      });

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }

      var currentArea = storeAreas.firstWhere((storeArea) => storeArea.areaId == storeTable.areaId, orElse: () => null);
      if (currentArea != null) {
        currentArea.storeTableList.add(result.data);
        notifyListeners();
      }

      toast('添加桌台成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //检查数据
  bool checkStoreTable(StoreTable storeTable) {
    if (storeTable.areaId == null) {
      toast('所属区域不可为空，请检查');
      return false;
    }

    if (storeTable.tableName == null || storeTable.tableName == '') {
      toast('桌台名称不可为空，请检查');
      return false;
    }

    if (storeTable.maxPerson == null) {
      toast('座位数不可为空，请检查');
      return false;
    }

    return true;
  }

  //删除桌台
  Future<bool> deleteStoreTable(StoreTable storeTable) async {
    try {
      showLoadingToast();

      var result = await api.deleteStoreTableById({'tableId': storeTable.tableId});

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }

      var currentArea = storeAreas.firstWhere((storeArea) => storeArea.areaId == storeTable.areaId, orElse: () => null);
      if (currentArea != null) {
        currentArea.storeTableList.removeWhere((table) => table.tableId == storeTable.tableId);
        notifyListeners();
      }

      toast('删除桌台成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //修改桌台
  Future<bool> updateStoreTable(StoreTable storeTable) async {
    if (!checkStoreTable(storeTable)) return false;

    try {
      showLoadingToast();

      var result = await api.updateStoreTable(storeTable);

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }

      var currentArea = storeAreas.firstWhere((storeArea) => storeArea.areaId == storeTable.areaId, orElse: () => null);
      if (currentArea != null) {
        var tableIndex = currentArea.storeTableList.indexWhere((table) => table.tableId == storeTable.tableId);
        if (tableIndex != -1) {
          currentArea.storeTableList[tableIndex] = storeTable;
          notifyListeners();
        }
      }

      toast('修改桌台成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //检查区域数据
  bool checkStoreArea(StoreArea storeArea) {
    if (storeArea.areaName == null || storeArea.areaName == '') {
      toast('区域名称不可为空，请检查');
      return false;
    }

    return true;
  }

  //新增区域
  Future<bool> plusStoreArea(StoreArea storeArea) async {
    if (!checkStoreArea(storeArea)) return false;

    try {
      showLoadingToast();

      var result = await api.addStoreArea({'areaName': storeArea.areaName});

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }
      storeAreas.add(result.data);
      notifyListeners();

      toast('添加区域成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //删除区域
  Future<bool> deleteStoreArea(StoreArea storeArea) async {
    try {
      showLoadingToast();

      var result = await api.deleteStoreAreaById({'areaId': storeArea.areaId});

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }
      storeAreas.removeWhere((area) => area.areaId == storeArea.areaId);
      notifyListeners();

      toast('删除区域成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //修改区域
  Future<bool> updateStoreArea(StoreArea storeArea) async {
    if (!checkStoreArea(storeArea)) return false;

    try {
      showLoadingToast();

      var result = await api.updateStoreArea({
        'areaId': storeArea.areaId,
        'areaName': storeArea.areaName,
      });

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }

      var currentArea = storeAreas.firstWhere((area) => area.areaId == storeArea.areaId, orElse: () => null);
      if (currentArea != null) {
        currentArea.areaName = storeArea.areaName;
        notifyListeners();
      }

      toast('修改区域成功');

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //检查批量添加数据
  bool checkBatchTable(BatchTable batchTable) {
    if (batchTable.storeArea == null) {
      toast('所属区域不可为空，请检查');
      return false;
    }

    if (batchTable.tableNumber == null) {
      toast('桌台数量不可为空，请检查');
      return false;
    }

    if (batchTable.seatNumber == null) {
      toast('座位数不可为空，请检查');
      return false;
    }

    return true;
  }

  //批量添加桌台
  Future<bool> plusBatchStoreTable(BatchTable batchTable) async {
    if (!checkBatchTable(batchTable)) return false;

    try {
      showLoadingToast();

      var result = await api.addTableByNum({
        'areaId': batchTable.storeArea.areaId,
        'areaName': batchTable.storeArea.areaName,
        'tableNum': batchTable.tableNumber,
        'maxPerson': batchTable.seatNumber,
        'tableName': batchTable.storeArea.areaName,
      });

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }

      var currentArea = storeAreas.firstWhere((item) => item.areaId == batchTable.storeArea.areaId, orElse: () => null);

      if (currentArea != null) {
        currentArea.storeTableList.addAll(result.data);
        notifyListeners();
      }

      toast('批量添加桌台成功');

      return true;
    } catch (e) {
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  //桌台排序
  sortTable(List<SortItemData<StoreTable>> tables) async {
    if (tables.length == 0) return;

    try {
      showLoadingToast();
      var result = await api.sortStoreTable({
        'storeTableList': tables.map((item) => item.value.tableId).toList(),
      });
      if (!result.successful()) {
        toast(result.msg);
        return;
      }

      var areaId = tables[0].value.areaId;

      var area = storeAreas.firstWhere((item) => item.areaId == areaId, orElse: () => null);
      if (area != null) {
        area.storeTableList = tables.map((item) => item.value).toList();
        notifyListeners();
      }

      toast('排序成功');
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  //区域排序
  sortArea(List<SortItemData<StoreArea>> areas) async {
    try {
      showLoadingToast();
      var result = await api.sortStoreArea({
        'areaIdList': areas.map((item) => item.value.areaId).toList(),
      });
      if (!result.successful()) {
        toast(result.msg);
        return;
      }
      storeAreas = areas.map((item) => item.value).toList();
      notifyListeners();
      toast('排序成功');

      Navigator.pop(GlobalPageContext.instance.context);
    } catch (e) {
      toast(Constant.httpServeErrText);
    } finally {
      hideLoadingToast();
    }
  }
}
